package lottery

import (
	"database/sql"
	"errors"
	"fmt"
	"geak/biz/m"
	"geak/libs/log"
	ts "geak/tools/strings"
	"go.uber.org/zap"
	"strings"
)

func (this *Service)GetLastestSSQ()(ssq *m.Lottery,err error) {
	ssqList,err := this.GetSSQList(0,1)
	if err != nil {
		return nil,err
	}
	if len(ssqList) == 1 {
		return ssqList[0],nil
	}else {
		return nil,errors.New("query rows len > 1")
	}
}

func (this *Service)GetSSQList(start int64,count int64)(ssqList []*m.Lottery,err error) {
	sqlStr := fmt.Sprintf("SELECT `code`,`date`,`red`,`blue`,`blue2`,`sales`,`pool_money`,`first_count`," +
		"`first_money`,`second_count`,`second_money`,`third_count`,`third_money` FROM `ssq`" +
		" ORDER BY `code` DESC LIMIT %d,%d",start,count)
	var (
		code  sql.NullString
		date  sql.NullString
		red	  sql.NullString
		blue  sql.NullString
		blue2 sql.NullString
		sales sql.NullString
		poolMoney sql.NullString
		firstCount sql.NullString
		firstMoney sql.NullString
		secondCount sql.NullString
		secondMoney sql.NullString
		thirdCount sql.NullString
		thirdMoney sql.NullString
	)
	rows, err := this.dao.DB.Query(sqlStr)
	if err != nil {
		log.Error(sqlStr,zap.Error(err))
		return
	}
	defer rows.Close()

	for rows.Next() {
		err = rows.Scan(&code, &date, &red, &blue, &blue2, &sales, &poolMoney, &firstCount,
			&firstMoney, &secondCount, &secondMoney, &thirdCount, &thirdMoney)
		if err != nil {
			log.Error("rows.Scan error",zap.Error(err))
			continue
		}
		ssq :=&m.Lottery{Name: "双色球",Type:0}
		ssq.Code = code.String
		ssq.Date = date.String
		ssq.Red = strings.Split(red.String,",")
		ssq.Blue = []string{blue.String,blue2.String}
		ssq.Sales = ts.Str2Int64(sales.String)
		ssq.PoolMoney =ts.Str2Int64(poolMoney.String)
		ssq.FirstCount = ts.Str2Int64(firstCount.String)
		ssq.FirstMoney = ts.Str2Int64(firstMoney.String)
		ssq.SecondCount = ts.Str2Int64(secondCount.String)
		ssq.SecondMoney = ts.Str2Int64(secondMoney.String)
		ssq.ThirdCount = ts.Str2Int64(thirdCount.String)
		ssq.ThirdMoney = ts.Str2Int64(thirdMoney.String)
		ssqList = append(ssqList,ssq)
	}
	err = rows.Err()
	if err != nil {
		log.Error("rows. error",zap.Error(err))
		return nil,err
	}
	return
}
